/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package es.decoroso.communicationAgent.comunicationServer;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.json.JSONObject;

/**
 * 
 * @author Daniel Klepel, Jesús Jiménez
 * @see http://tutorials.jenkov.com/java-multithreaded-servers/thread-pooled-server.html
 */
public class WorkerRunnable implements Runnable {

	protected Socket clientSocket = null;
	protected String serverText = null;
	private final CommunicationServer com;

	public WorkerRunnable(Socket clientSocket, String serverText,
			CommunicationServer com) {
		this.clientSocket = clientSocket;
		this.serverText = serverText;
		this.com = com;
	}

	public void run() {
		sendAgents();
	}

	private synchronized void sendAgents() {

		try {
			InputStream input = clientSocket.getInputStream();
			OutputStream output = clientSocket.getOutputStream();
			boolean always = true;

			while (always) {
				synchronized (this) {
					wait();
				}

				JSONObject js = com.getMessages().toJSON();
				output.write((js.toString() + "\n").getBytes());
				output.flush();

			}
			output.close();
			input.close();
		} catch (IOException e) {
			// report exception somewhere.
			e.printStackTrace();
		} catch (InterruptedException ex) {
			Logger.getLogger(WorkerRunnable.class.getName()).log(Level.SEVERE,
					null, ex);
		}
	}
}